package com.jiazhong.mingxing.boot.boot07.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.mingxing.boot.boot07.bean.User;
import com.jiazhong.mingxing.boot.boot07.config.JwtConfig;
import com.jiazhong.mingxing.boot.boot07.mapper.UserMapper;
import com.jiazhong.mingxing.boot.boot07.service.UserService;
import com.jiazhong.mingxing.boot.boot07.util.JsonResult;
import com.jiazhong.mingxing.boot.boot07.util.ResultTool;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JsonResult login(User user) {
        // 1. 查询数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        queryWrapper.eq("password", user.getPassword());
        User one = getOne(queryWrapper);
        // 2. 判断账号或者密码是否正确
        // 2.1 错误
        if (one == null) {
            return ResultTool.fail("账号或者密码错误", 400);
        }
        // 2.2 正确
        // 3. 生成token令牌
        String token = JwtConfig.getJwtToken(one);
        // 4. 保存token令牌
        stringRedisTemplate.opsForValue().set("token:" + one.getId(), token, 1, TimeUnit.DAYS);
        // 5. 返回token令牌
        return ResultTool.success(token);
    }

    @Override
    public JsonResult isLogin(String token) {
        // 1. 检查token是否篡改过
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            return ResultTool.fail("用户没有登陆", 401);
        }
        // 2. 获取到token中保存的id信息
        Claims claims = JwtConfig.parseJWT(token);
        Object id = claims.get("id");
        // 3. 获取到redis中存储的token
        String redisToken = stringRedisTemplate.opsForValue().get("token:" + id);
        // 4. 检查token是否一致
        return Objects.equals(token, redisToken) ? ResultTool.success("success") : ResultTool.fail("用户没有登陆", 401);
    }
}
